﻿using System;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using AifMessageHeaderEditor.Lib.Data.MessageDocument;
using AifMessageHeaderEditor.Lib.File;

namespace AifMessageHeaderEditor.Gui
{
    public partial class frmHeaderEditor : Form
    {
        #region private CONSTS

        private const string ERROR_DIRECTORY_NOT_EXISTING = "Directory does not exsit. Please select another Aif" +
                    "message-file destination directory.";
        private const string ERROR_MESSAGE_NOT_VALID = "Message not valid:"; 
        private const string GUID_FORMAT = "{{{0}}}";
        private const string XML_FILE_FILTER =
            "Xml files (*.xml)|*.xml|Aif message-files (*.aifx)|*.aifx";
        private const string XML_FILE_EXTENTION = "xml";
        private const string FILE_MULTIPLE_SELECTION_EXCEPTION =
            "Multiple file-selection is not supported.";
        private const string FILE_ERROR_READING_EXCEPTION =
            "Error while reading File:";
        private const string FILE_NOT_EXIST_EXCEPTION =
            "File does not exist.";


        #endregion

        public frmHeaderEditor(string fileName)
        {
            InitializeComponent();
            this.IBSFileData.Add(MessageFile.Instance.XmlFile);
            fdgXmlFile.FileName = string.Empty;
            fdgXmlFile.Filter = XML_FILE_FILTER;
            fdgXmlFile.DefaultExt = XML_FILE_EXTENTION;
            fdgXmlFile.FileOk += new CancelEventHandler(fdgXmlFile_FileOk);

            if (fileName != string.Empty)
            {
                fdgXmlFile.FileName = fileName;
                ReadDocument(fileName);
            }
        }

        #region events

        void fdgXmlFile_FileOk(object sender, CancelEventArgs e)
        {
            if (e.Cancel)
                return;

            ReadDocument(fdgXmlFile.FileName);
        }

        private void btnXmlFile_Click(object sender, EventArgs e)
        {
            DialogResult result = fdgXmlFile.ShowDialog();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveDocument(MessageFile.Instance.XmlFile.SourceFilename,
                MessageFile.Instance.XmlFile.DestinationDirectory,
                MessageFile.Instance.XmlFile.FileOwnerName);
        }

        private void btnDestination_Click(object sender, EventArgs e)
        {
            fbdDestinationFolder.SelectedPath =
                System.IO.Path.GetDirectoryName(fdgXmlFile.FileName);
            DialogResult result = fbdDestinationFolder.ShowDialog();
            MessageFile.Instance.XmlFile.DestinationDirectory = fbdDestinationFolder.SelectedPath;
        }

        private void frmHeaderEditor_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

            if (files.Length > 1)
            {
                MessageBox.Show(FILE_MULTIPLE_SELECTION_EXCEPTION);
                return;
            }
            fdgXmlFile.FileName = files[0];
            ReadDocument(files[0]);
        }

        private void frmHeaderEditor_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
            {
                e.Effect = DragDropEffects.All;
            }
        }

        #endregion

        #region Textboxes

        //TODO: integrate into binding
        private void SetEnabled(bool isActive)
        {
            gbXmlFileInformation.Enabled = isActive;
            btnSave.Enabled = isActive;
            txtSave.Enabled = isActive;
            btnDestination.Enabled = isActive;
        }

        #endregion

        #region Save/Read Document

        private void SaveDocument(string sourceFile,
            string destinationDirectory,
            string username)
        {
            if (System.IO.Directory.Exists(destinationDirectory))
            {
                MessageFile.Instance.MessageFileInformation.HeaderNode.MessageId =
                    string.Format(GUID_FORMAT, Guid.NewGuid().ToString());
                try
                {
                    MessageFile.Instance.WriteDocument();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show(ERROR_DIRECTORY_NOT_EXISTING);
            }
        }


       private void ReadDocument(string filename)
        {
            try
            {
                if (System.IO.File.Exists(filename))
                {
                    if (!MessageFile.Instance.LoadDocument(filename))
                    {
                        if (MessageFile.Instance.ValidationMessageList.Count > 0)
                        {
                            StringBuilder sb = new StringBuilder();
                            foreach (string message in MessageFile.Instance.ValidationMessageList)
                            {
                                sb.Append(message + Environment.NewLine);
                            }
                            throw new Exception(ERROR_MESSAGE_NOT_VALID +
                                Environment.NewLine +
                                sb.ToString());
                        }
                    }
                    this.IBSBody.Add(MessageFile.Instance.MessageFileInformation.BodyNode);
                    this.IBSHeader.Add(MessageFile.Instance.MessageFileInformation.HeaderNode);
                    SetEnabled(true);
                }
                else
                {
                    this.IBSBody.Remove(MessageFile.Instance.MessageFileInformation.BodyNode);
                    MessageFile.Instance.ResetDocument();
                    throw new Exception(FILE_NOT_EXIST_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(FILE_ERROR_READING_EXCEPTION +
                    Environment.NewLine + ex.Message);
                MessageFile.Instance.ResetDocument();
                SetEnabled(false);
            }
        }

        #endregion
    }
}